<template xmlns:el-col="http://www.w3.org/1999/xhtml" xmlns="http://www.w3.org/1999/html">
  <div class="echarts_container">
    <el-row class="main_row">
      <el-col :span="24">
        <div class="welcome">
          <div class="content">
            <div class="avatar">
              <el-avatar :src="getCurrentUserAvater" fit="cover" :size="80"/>
            </div>
            <div class="text">
              <div class="welcome_text">
                {{ getCurrentTimeDesc }}，{{ getCurrentUser }}！欢迎登录
              </div>
              <div class="system_desc">
                一站式智能管理解决方案，帮助你、高效管理客户、快速提升业绩
              </div>
            </div>
          </div>
          <div class="bg">
            <img src="../../assets/Agreements.png" class="work_bg"/>
          </div>
        </div>
      </el-col>
    </el-row>
    <el-row class="main_row">
      <el-col :span="12" class="row_col">
        <div class="order_amount" v-loading="amountLoading">
          <el-row class="inner_top">
            <el-col :span="18" class="amount_title">销售额汇总分析</el-col>
            <el-col :span="6">
              <el-select v-model="amountValue" @change="getTotalAmount(amountValue)" placeholder="请选择汇总类型"
                         style="width: 150px" size="small">
                <el-option
                    v-for="(item,index) in typeOptions"
                    :key="index"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </el-col>
          </el-row>
          <el-row class="inner_row">
            <el-col :span="24" class="inner_col">
              <div class="static_title">订单销售总金额</div>
              <div class="static_result">{{ formatNumber(amount.totalAmount) }}</div>
              <div class="proportion">
                <span v-if="!amount.isConsistent">{{ amount.compared }}</span>
                <span v-if="getPercent"> {{ getPercent }}%</span>
                <span v-if="amount.isConsistent">{{ amount.compared }} 持平</span>
                <i class="el-icon-caret-top" style="color: #ff4040" v-if="amount.isProfit && !amount.isConsistent"></i>
                <i class="el-icon-caret-bottom" style="color: #21df21"
                   v-if="!amount.isProfit && !amount.isConsistent"></i>
                <el-tooltip effect="dark" :content="amount.historyTitle + formatNumber(amount.historicalAmount)"
                            placement="top-start">
                  <i class="el-icon-warning-outline"></i>
                </el-tooltip>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-col>
      <el-col :span="12" class="row_col">
        <div class="product_rank">
          <el-row class="box_top">
            <el-col :span="18" class="top_title">热门产品销售占比</el-col>
            <el-col :span="6">
              <el-select v-model="productTypeValue" @change="changeType('product')" placeholder="请选择汇总类型"
                         style="width: 150px" size="small">
                <el-option
                    v-for="(item,index) in typeOptions"
                    :key="index"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24" class="bottom_chart">
              <div id="product_chart"></div>
            </el-col>
          </el-row>
        </div>
      </el-col>
    </el-row>
    <el-row class="main_row">
      <el-col :span="12" class="row_col">
        <div class="order">
          <el-row class="box_top">
            <el-col :span="16" class="top_title">订单趋势</el-col>
            <el-col :span="8">
              <el-select v-model="orderTypeValue" @change="changeType('order')" placeholder="请选择汇总类型"
                         style="width: 150px" size="small">
                <el-option
                    v-for="(item,index) in typeOptions"
                    :key="index"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </el-col>
          </el-row>
          <el-row class="bottom_chart">
            <div id="order_chart"></div>
          </el-row>
        </div>
      </el-col>
      <el-col :span="12" class="row_col">
        <div class="order">
          <el-row class="box_top">
            <el-col :span="16" class="top_title">客户趋势</el-col>
            <el-col :span="8">
              <el-select v-model="customTypeValue" @change="changeType('custom')" placeholder="请选择汇总类型"
                         style="width: 150px" size="small">
                <el-option
                    v-for="(item,index) in typeOptions"
                    :key="index"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </el-col>
          </el-row>
          <el-row class="bottom_chart">
            <div id="custom_chart"></div>
          </el-row>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts';
// import  {Chart}  from '@antv/g2';

export default {
  name: "echarts",
  components: {
    // HelloWorld
  },
  data() {
    return {
      form: {
        customNum: '',
        orderNum: '',
        productNum: '',
      },
      orderData: {
        date: '',
        quantity: null,
      },
      orderChart: null,
      orderCount: [],
      orderSubscript: [],
      customSubscript: [],
      customCount: [],
      orderTitle: "年度订单数量汇总",
      customTitle: "年度客户数量汇总",
      customChart: null,
      orderTypeValue: "year",
      customTypeValue: "year",
      typeOptions: [
        {value: "year", label: "年度"},
        {value: "month", label: "月度"},
        {value: "week", label: "周度"}
      ],
      currentTime: new Date(),
      amountValue: 'year',
      amount: {
        isConsistent: false,
        totalAmount: "",
        isProfit: true,
        compared: "同步去年",
        historyTitle: "去年总销售额",
        historicalAmount: "",
        percent: "",
      },
      amountLoading: false,
      productChart: null,
      productCountData: [],
      productTitle:"年度热门产品销售数量汇总",
      productTypeValue:"year",
    }
  },
  computed: {
    getCurrentTimeDesc() {
      const hours = this.currentTime.getHours();
      if (hours >= 5 && hours < 12) {
        return "上午好";
      } else if (hours >= 12 && hours < 14) {
        return "中午好";
      } else if (hours >= 14 && hours < 18) {
        return "下午好";
      } else {
        return "晚上好";
      }
    },
    getCurrentUser() {
      const loginInfo = localStorage.getItem("logininfo");
      const user = JSON.parse(loginInfo);
      return user.account;
    },
    getCurrentUserAvater() {
      const loginInfo = localStorage.getItem("logininfo");
      const user = JSON.parse(loginInfo);
      return user.avatar;
    },
    getPercent() {
      const amount = this.amount;
      const nowAmount = amount.totalAmount;
      const lastAmount = amount.historicalAmount;
      if (lastAmount === 0) {
        // 如果去年金额为0，则无法计算百分比变化
        return "";
      }
      const changeAmount = nowAmount - lastAmount;
      const percent = (changeAmount / lastAmount) * 100;
      if (percent > 0) {
        return percent.toFixed(2);
      } else if (percent < 0) {
        return Math.abs(percent).toFixed(2);
      }
    }
  },
  mounted() {
    // this.product();
    // this.orderNumber();
    // this.coustom();
    this.getOrderCount('year').then(res => {
      this.drawOrderCharts();
    });
    this.getCustomCount('year').then(res => {
      this.drawCustomCharts();
    });
    this.getProductCount('year').then(res => {
      this.drawProductCharts();
    });
    this.getTotalAmount('year');

  },
  methods: {
    drawProductCharts() {
      this.productChart = echarts.init(document.getElementById('product_chart'));
      const option = {
        backgroundColor: '#F5F5F5',
        tooltip: {
          trigger: 'item'
        },
        legend: {
          top: '5%',
          left: 'center'
        },
        series: [
          {
            name: '产品销售数量',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 20,
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: this.productCountData
          }
        ]
      };
      this.productChart.setOption(option);
    },
    getProductCount(type) {
      return new Promise((resolve, reject) => {
        if (type === 'year') {
          this.productTitle = "年度热门产品销售数量汇总";
        } else if (type === 'month') {
          this.productTitle = "月度热门产品销售数量汇总";
        } else if (type === 'week') {
          this.productTitle = '本周热门产品销售数量汇总';
        }
        this.$http.post("/orderList/getHotProductCount",this.$qs.stringify({type:type})).then((res)=>{
          if(res.data.success){
            this.productCountData = res.data.resultObj;
            resolve();
          }
        })
      })
    },
    getTotalAmount(type) {
      if (type === 'year') {
        this.amount.historyTitle = '去年总销售额';
        this.amount.compared = '同比去年';
      } else if (type === 'month') {
        this.amount.historyTitle = '上月总销售额';
        this.amount.compared = '同比上月';
      } else if (type === 'week') {
        this.amount.historyTitle = '上周总销售额';
        this.amount.compared = '同比上周'
      }
      this.amountLoading = true;
      this.$http.post("/orderList/getTotalAmount", this.$qs.stringify({type: type})).then((res) => {
        if (res.data.success) {
          this.amount.isProfit = res.data.resultObj.isProfit;
          this.amount.totalAmount = res.data.resultObj.totalAmount;
          this.amount.historicalAmount = res.data.resultObj.lastAmount;
          this.amount.isConsistent = res.data.resultObj.isConsistent;
          this.amountLoading = false;
        } else {
          this.amountLoading = false;
        }
      })
    },
    formatNumber(number) {
      let str = number.toString();
      let integerPart = str.split('.')[0].split('');
      let decimalPart = str.split('.')[1] ? str.split('.')[1].split('') : [];

      // 对整数部分进行千分位格式化
      for (let i = integerPart.length - 3; i > 0; i -= 3) {
        integerPart[i] = ',' + integerPart[i];
      }

      // 对小数部分进行千分位格式化
      for (let i = decimalPart.length - 3; i > 0; i -= 3) {
        decimalPart[i] = ',' + decimalPart[i];
      }

      // 拼接整数部分和小数部分
      return integerPart.join('') + (decimalPart.length ? '.' + decimalPart.join('') : '');
    },
    changeType(type) {
      if (type === 'order') {
        this.getOrderCount(this.orderTypeValue).then(res => {
          this.drawOrderCharts();
        });
      } else if (type === 'custom') {
        this.getCustomCount(this.customTypeValue).then(res => {
          this.drawCustomCharts()
        })
      }else if( type === 'product'){
        this.getProductCount(this.productTypeValue).then(res => {
          this.drawProductCharts()
        })
      }

    },
    getCustomCount(type) {
      return new Promise((resolve, reject) => {
        if (type === 'year') {
          this.customTitle = "年度客户数量汇总";
        } else if (type === 'month') {
          this.customTitle = "月度客户数量汇总";
        } else if (type === 'week') {
          this.customTitle = '本周客户数量汇总';
        }
        this.$http.post('/customMycustom/getCustomDataCount', this.$qs.stringify({type: type})).then(res => {
          if (res.data.success) {
            this.customCount = res.data.resultObj.count;
            this.customSubscript = res.data.resultObj.subscript;
            resolve();
          } else {
            reject('error');
          }
        })
      })
    },
    getOrderCount(type) {
      return new Promise((resolve, reject) => {
        if (type === 'year') {
          this.orderTitle = "年度订单数量汇总";
        } else if (type === 'month') {
          this.orderTitle = "月度订单数量汇总";
        } else if (type === 'week') {
          this.orderTitle = '周订单数量汇总';
        }
        this.$http.post('/orderList/getOrderDataCount', this.$qs.stringify({type: type})).then(res => {
          if (res.data.success) {
            this.orderCount = res.data.resultObj.count;
            this.orderSubscript = res.data.resultObj.subscript;
            resolve();
          } else {
            reject('error');
          }
        })
      })
    },
    // coustom() {
    //   this.$http.get('/customMycustom/num').then(response => {
    //     this.form.customNum = response.data
    //     console.log(this.form.productNum)
    //   }).catch(error => {
    //     console.error("请求失败，处理错误:", error)
    //   })
    // },
    // product: function () {
    //   this.$http.get('/productList/num').then(response => {
    //     this.form.productNum = response.data
    //
    //   }).catch(error => {
    //     console.error("请求失败，处理错误:", error)
    //   })
    // },
    // orderNumber: function () {
    //   this.$http.get("/orderList/num").then(response => {
    //     this.form.orderNum = response.data
    //     console.log("aaaaa" + response.data)
    //   }).catch(error => {
    //     console.error("请求失败，处理错误:", error)
    //   })
    // },
    //获取订单数据
    // getChartsData() {
    //   this.$http.get("/orderList/Time").then(res => {
    //     this.orderData = res.data;
    //   })
    // },
    drawCustomCharts() {
      this.customChart = echarts.init(document.getElementById("custom_chart"));
      this.customChart.setOption({
        backgroundColor: '#F5F5F5',
        color: "#fac858",
        title: {
          text: this.customTitle,
        },
        tooltip: {},
        xAxis: {
          type: 'category',
          data: this.customSubscript,
          boundaryGap: false,
          axisLabel: {
            show: false,//隐藏刻度值
            interval: 0,
            textStyle: {//x轴字体样式
              margin: 20
            }
          },
        },
        yAxis: {
          type: 'value',
          minInterval: 1,
          boundaryGap: false
        },
        series: [
          {
            name: "订单数量",
            smooth: true,
            type: "line",
            data: this.customCount, //就一个一个集合按照状态升序的
            label: {
              show: true,
              position: 'top',
              formatter: '{c}'
            },
            areaStyle: {}
          },
        ],
        dataZoom: [ // DataZoom组件配置
        ]
      });
    },
    drawOrderCharts() {
      this.orderChart = echarts.init(document.getElementById("order_chart"));
      this.orderChart.setOption({
        backgroundColor: '#F5F5F5',
        title: {
          text: this.orderTitle,
        },
        tooltip: {},
        xAxis: {
          type: 'category',
          data: this.orderSubscript,
          boundaryGap: false,
          axisLabel: {
            show: false,//隐藏刻度值
            interval: 0,
            textStyle: {//x轴字体样式
              margin: 20
            }
          },
        },
        yAxis: {
          type: 'value',
          minInterval: 1,
          boundaryGap: false
        },
        series: [
          {
            name: "订单数量",
            smooth: true,
            type: "line",
            data: this.orderCount, //就一个一个集合按照状态升序的
            label: {
              show: true,
              position: 'top',
              formatter: '{c}'
            },
            areaStyle: {}
          },
        ],
        dataZoom: [ // DataZoom组件配置
        ]
      });
    },
  },
}
;
</script>
<style lang="scss" scoped>
.chart-container {
  width: 100%;
  float: left;
}

/*.chart div {
    height: 400px;
   float: left;
}*/
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 38px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}

.box-card {
  height: 180px;
  margin-left: 150px;
  margin-bottom: 120px;
  margin-top: 20px;
}

.el-icon-s-ticket {
  font-size: 50px;
  color: #5a90e3;
}

.el-icon-user {
  font-size: 50px;
  color: #5a90e3;
}

.el-icon-s-management {
  font-size: 50px;
  color: #5a90e3;
}

.bottom {
  margin-top: 10px;
  display: flex;
}

.bottom-left {
  width: 150px;
}

.home {
  width: 1300px;
  height: 800px;
  /*background-color: pink;*/
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap;
}

.echarts_container {
  width: 100%;
}

.main_row {
  margin: 20px 0;

  .row_col {
    padding: 0 5px;
  }

  .inner_top {
    padding: 10px 20px;
    height: 15%;

    .amount_title {
      font-size: 18px;
      font-family: '黑体';
      font-weight: bolder;
    }
  }

  .inner_row {
    height: 85%;

    .inner_col {
      height: 100%;
      padding: 20px 20px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;

      .static_title {
        font-size: 14px;
        color: #8d8d8d;
      }

      .static_result {
        font-size: 30px;
        font-family: '黑体';
        font-weight: bolder;
      }

      .proportion {
        color: #8d8d8d;
        font-size: 14px;
      }
    }
  }

  .product_rank {
    height: 300px;
    background-color: #f5f5f5;
    border-radius: 10px;

    .box_top {
      padding: 15px 0;

      .top_title {
        padding: 0 20px;
        font-size: 18px;
        font-family: '黑体';
        font-weight: bolder;
      }
    }
    .bottom_chart{
      display: flex;
      justify-content: center;
      align-items: center;
    }
    #product_chart{
      width: 600px;
      height: 200px;
    }
  }
}

.welcome {
  width: 100%;
  height: 200px;
  display: flex;
  align-items: center;
  background: linear-gradient(to bottom, #3994ff, #1c5eff);
  border-radius: 10px;

  .content {
    width: 450px;
    height: 150px;
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    position: absolute;
    left: 150px;

    .avatar {
      padding: 25px 25px;
    }

    .system_desc {
      padding: 5px 0;
      font-size: 14px;
      color: #d5e5ff;
    }
  }

  .welcome_text {
    padding: 5px 0;
    font-size: 24px;
    color: #fff;
  }
}

.bg {
  position: absolute;
  height: 200px;
  width: 335px;
  right: 200px;

  .work_bg {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

.order {
  width: 100%;
  height: 380px;
  background-color: #f5f5f5;
  border-radius: 10px;

  .box_top {
    padding: 15px 0;

    .top_title {
      padding: 0 20px;
      font-size: 18px;
      font-family: '黑体';
      font-weight: bolder;
    }
  }

  .bottom_chart {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  #order_chart {
    width: 600px;
    height: 300px;
  }

  #custom_chart {
    width: 600px;
    height: 300px;
  }
}

.order_amount {
  height: 300px;
  background-color: #f5f5f5;
  border-radius: 10px;
}

</style>
